package com.cdsz.boot.system.activity;

import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.delegate.event.impl.ActivitiEntityEventImpl;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.springframework.stereotype.Component;

import java.util.function.Consumer;

@Slf4j
@Component
public class ExecutionListener implements ActivitiEventListener {


    @Override
    public void onEvent(ActivitiEvent event) {
        log.info("========================ExecutionListener========================");
        switch (event.getType()) {
            case TASK_CREATED:
                log.info("===================任务创建事件===================");
                this.taskCreate(event);
                log.info("================================================");
                break;
            case TASK_ASSIGNED:
                log.info("===================任务分配事件===================");
                this.taskAssigned(event);
                log.info("=================================================");
                break;
            case TASK_COMPLETED:
                log.info("===================任务完成事件===================");
                this.taskComplete(event);
                log.info("==================================================");
                break;
            default:
                log.info("Event received: {}", event.getType());
        }
    }

    @Override
    public boolean isFailOnException() {
        return false;
    }

    private void taskCreate(ActivitiEvent event) {
        doExecutionAfter(event, taskEntity -> {});
    }

    private void taskAssigned(ActivitiEvent event) {
        doExecutionAfter(event, taskEntity -> {});
    }

    private void taskComplete(ActivitiEvent event) {
        doExecutionAfter(event, taskEntity -> {});

    }

    public void doExecutionAfter(ActivitiEvent activitiEvent, Consumer<TaskEntity> consumer) {
        ActivitiEntityEventImpl activitiEntityEvent = (ActivitiEntityEventImpl) activitiEvent;
        TaskEntity taskEntity = (TaskEntity) activitiEntityEvent.getEntity();
        log.info("===== Id:{}", taskEntity.getId());
        log.info("===== Name:{}", taskEntity.getName());
        log.info("===== Assignee:{}", taskEntity.getAssignee());
        log.info("===== IdentityLinks:{}", taskEntity.getIdentityLinks());
        log.info("===== Variables:{}", taskEntity.getVariables());
        consumer.accept(taskEntity);
    }
}
